require 'localization_settings'
require 'switch_language'
require 'additional_tag_functions'
require 'caboose_memcached'

class ApplicationController < ActionController::Base
  include LocalizationSettings
  include Franck::SwitchLanguage
  include ExceptionNotifiable
  include Franck::AdditionalTagFunctions
  include CabooseMemcached

  before_filter :locale, :except => "set_lang"
  before_filter :login_user_from_cookie
 # before_filter :login_candidate_from_cookie
  before_filter :default_page_title

	def send_email(message)
    message_body = []
    message.each do |key, value|
      message_body << key + ' : '
      message_body << value
      message_body << "\n"
    end
    @message = Hash.new
    @message['body'] = message_body
    @message['recipient'] = message['recipient'] || 'contact'
    @message['subject'] = message['subject'] || "[EJ] Envoyé via un formulaire"
    Batman::deliver_message(@message)
  end

	def set_bottomlinks
		@bottomlinks = Article.ez_find(:first, :include => [:category, :tags, :taggings]) do |article, category, tag, tagging|
			tag.name == "bottomlinks"
		 	category.name ==	session['lang']
			article.published == 1
		end
	end

	def set_toplinks
		@toplinks = Article.ez_find(:first, :include => [:category, :tags, :taggings]) do |article, category, tag, tagging|
			tag.name == "toplinks"
		 	category.name ==	session['lang']
			article.published == 1
		end
	end

	def set_about
		@about = Article.ez_find(:first, :include => [:category, :tags, :taggings]) do |article, category, tag, tagging|
			tag.name == "about"
		 	category.name ==	session['lang']
			article.published == 1
		end
	end
	
	def set_our_services
		@our_services = Article.ez_find(:first, :include => [:category, :tags, :taggings]) do |article, category, tag, tagging|
			tag.name == "ourservices"
		 	category.name ==	session['lang']
			article.published == 1
		end
	end
	
	def set_contact_us
		@contact_us = Article.ez_find(:first, :include => [:category, :tags, :taggings]) do |article, category, tag, tagging|
			tag.name == "contactus"
		 	category.name ==	session['lang']
			article.published == 1
		end
	end

	def set_menu
		@lang_category = Category.find(:first, :conditions => ["name = ?",session['lang']])
		@menu = @lang_category.children
	end

	def set_current_top_category
		@article = Article.find(:first, :conditions => ["permalink = ? AND published = 1 ", params[:id] ])

		unless @article.nil?
			@article_category = @article.category
		end

		@category = Category.find_by_permalink(params[:id]) || @article_category
		unless @category.nil?
			@cat = @category.ancestors
			@cat << @category
			@cat.flatten!
			current_top_category = @cat & @menu
			@current_top_category = current_top_category[0]
		else
			@current_top_category = nil
		end
			
		
	end

  def default_page_title
    @page_title = "Eurojob Consulting"
  end

  def login_user_from_cookie
    return unless session[:user].nil? && cookies[:auth_token]
    self.current_user = User.find_by_remember_token(cookies[:auth_token])
  end
  
  # saving the last request uri
  after_filter :save_last_request_uri
  def save_last_request_uri
    if request.get? and response.redirected_to.nil? and request.env["PATH_INFO"] != "/cv/accord"
      session[:last_request_uri] = session[:this_request_uri]
      session[:this_request_uri] = request.request_uri
      session[:last_unique_request_uri] = session[:last_request_uri] if session[:this_request_uri] != session[:last_request_uri]
    end
  end

  def show_tags_list
    @tags_list = Tagging.find(:all).collect { |tagging| tagging.tag }.uniq
    render false
  end
  
  helper_method :last_request_uri
  def last_request_uri
    if session[:this_request_uri] == request.request_uri
      if session[:this_request_uri] == session[:last_request_uri]
        session[:last_unique_request_uri]
      else
        session[:last_request_uri]
      end
    else
      session[:this_request_uri]
    end
  end


  helper_method :toggable_location
  def toggable_location(root, lvl = 1)
    html = []
    unless root.children.size == 0
      html << "<ul id=\"location_#{root.id}\">"
      root.children.each do |child|
        html << "<li>#{child.name}</li>"
      end
      html << "</ul>"
    end

    return html if lvl == 1

    root.children.each do |lvl1|
      unless lvl1.children.size == 0
        html << "<ul id=\"location_#{lvl1.id}\" style=\"display:none;\">"
        lvl1.children.each do |child|
          html << "<li>#{child.name}</li>"
        end
        html << "</ul>"
      end
    end

    return html if lvl == 2

    root.children.each do |lvl1|
      lvl1.children.each do |lvl2|
        unless lvl2.children.size == 0
          html << "<ul id=\"location_#{lvl2.id}\" style=\"display:none;\">"
          lvl2.children.each do |child|
            html << "<li>#{child.name}</li>"
          end
          html << "</ul>"
        end
      end
    end
    return html
  end

  def paginate_collection(collection, options={})
    default_options = { :per_page => 10, :page => 1 }
    options = default_options.merge(options)
    pages = Paginator.new(self, collection.size, options[:per_page], options[:page])
    first = pages.current.offset
    last = [first + options[:per_page], collection.size].min
    slice = collection[first...last]
    return [pages, slice]
  end
  
  # paginator for ferret search  
  def pages_for(size, options = {})
    default_options = {:per_page => 3}
    options = default_options.merge options
    pages = Paginator.new self, size, options[:per_page], (params[:page]||1)
    pages
  end
  

  protected

  # need by hook login_user_from_cookie (not very DRY)
  helper_method :current_user
  def current_user
    @current_user ||= session[:user] ? User.find_by_id(session[:user]) : nil
  end

  def current_user=(new_user)
    session[:user] = new_user.nil? ? nil : new_user.id
    @current_user = new_user
  end

end
